<?php

class Suggest extends CActiveRecord {

    public $files;

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return 'Suggest';
    }

    public function relations() {
        return array(
            'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),
            'comments' => array(self::HAS_MANY, 'Comment', 'post_id', 'condition' => 'type = 2', 'together' => false),
            'rt' => array(self::HAS_MANY, 'Rating', 'item_id', 'together' => false),
            'cont_comments' => array(self::STAT, 'Comment', 'post_id', 'condition' => 'type = 2'),
            'tags' => array(self::MANY_MANY, 'Tags', 'TagsSuggest(item_id, tag_id)', 'together' => false),);
    }

    public function beforeValidate() {
        if($this->isNewRecord) {
            $this->t_create = time();
            $this->t_update = time();
        }
        $this->title = trim(strip_tags($this->title));
        return true;
    }

    public function up() {
        $this->t_update = time();
        $this->save();
    }

    public function attributeLabels() {
        return array(
            'title' => 'Название',
            'text' => 'Описание предложения',
            'tags' => 'Теги (через запятую)',
            'send_email' => 'Оповещать об ответах на E-Mail',
            'files' => "Добавить файл (.jpg, .gif, .png, .doc, .docx, .xls, .xlsx) - размером не более 5Mb"
        );
    }

    public function getStatusName() {
        if($this->status == 0) {
            return "Активно";
        } else {
            return "Закрыто";
        }
    }

    public function beforeDelete() {
        // delete tegsSuggest
        TagsSuggest::model()->deleteAll("item_id = ?", array($this->id));
        // delete all comment
        $criteria = new CDbCriteria();
        $criteria->condition = "post_id = :post_id AND type = :type";
        $criteria->params = array(":post_id" => $this->id, ":type" => Comment::TYPE_SUGGEST);
        $comments = Comment::model()->findAll($criteria);
        foreach($comments as $comment) {
            $comment->delete();
        }
        //delete file
        if(!is_null($this->files)) {
            $path_parts = pathinfo(BSD . $this->files);
            @unlink(BSD . $this->files);
            $valid_extensions = array('gif', 'jpg', 'png');
            if(in_array($path_parts['extension'], $valid_extensions)) {
                @unlink($path_parts['dirname'] . "/prew_" . $path_parts['basename']);
            }
        }
        return parent::beforeDelete();
    }

    public function getTagIds() {
        $ids = array();
        foreach($this->tags as $tag) {
            $ids[] = $tag->id;
        }
        return $ids;
    }

    public function getDownloadLink() {
        if($this->files) {
            $name = substr(strrchr($this->files, '/service'), 1);
            return '<b class="clip">Скачать:</b> <a class="download" href="' . $this->files . '">' . $name . '</a>  ';
        }
    }

    public function findSimilarService($limit) {
        $ids = TagsService::getItemIds($this->getTagIds());
        $criteria = new CDbCriteria();
        $criteria->limit = $limit;
        $criteria->order = "t.t_create";
        $criteria->addInCondition('id', $ids);
        $criteria->addNotInCondition('id', array($this->id));
        return Service::model()->findAll($criteria);
    }

    public function findSimilarSuggest($limit) {
        $ids = TagsSuggest::getItemIds($this->getTagIds());
        $criteria = new CDbCriteria();
        $criteria->limit = $limit;
        $criteria->order = "t.t_create";
        $criteria->addInCondition('id', $ids);
        $criteria->addNotInCondition('id', array($this->id));
        return Suggest::model()->findAll($criteria);
    }

    public static function search($criteria, $pagination = false, $isSort = false, $paginationLimit = false) {
        $params = array('criteria' => $criteria);

        if($pagination) {
            $paginationLimit = $paginationLimit ? $paginationLimit : Y::param("countInPage");
            $params['pagination'] = array('pageSize' => $paginationLimit);
        }
        if($isSort) {
            $sort = new CSort();
            $sort->sortVar = 'sort';
            $sort->defaultOrder = 't.t_update DESC';
            $sort->multiSort = true;
            $sort->attributes = array('t_create' => array('asc' => 't.t_update ASC', 'desc' => 't.t_update DESC', 'label' => 'дате',), 'status' => array('asc' => 't.status ASC', 'desc' => 't.status DESC', 'label' => 'статусу',),);
            $params['sort'] = $sort;
        }

        $dependency = new CDbCacheDependency('SELECT MAX(t_update) FROM Suggest');
        $params['cache'] = array(3600, $dependency);

        return new EActiveDataProviderEx('Suggest', $params);
    }
}
